package com.example.basic_ui_demo.view.news

import android.util.Log
import com.example.basic_ui_demo.data_class.news.NewsJson
import com.example.basic_ui_demo.view.TAG
import com.example.basic_ui_demo.view_model.NewsViewModel

fun newsJsonCallback(newsJson: NewsJson, newsViewModel: NewsViewModel, isBack: Boolean) {
    Log.d(TAG, newsJson.msg)
    val newsList = newsJson.result?.newslist
    if (newsList != null) {
        for (news in newsList) {
            news.picUrl = changeUrl(news.picUrl)
            Log.d("MyTag", "title: ${news.title},picUrl: ${news.picUrl}")
        }
        for(news in newsList)
            if(isBack)
                newsViewModel.addNews(news)
            else
                newsViewModel.addNewsFront(news)
    } else {
        Log.e(TAG, "no newsList")
    }
}

fun bannerCallback(newsJson: NewsJson, viewModel: NewsViewModel){
    Log.d(TAG,"call banner callback")
    val newsList = newsJson.result?.newslist
    if(!newsList.isNullOrEmpty()){
        newsList.forEach {
            it.picUrl = changeUrl(it.picUrl)
        }
        viewModel.changeBanner(newsList)
    }else
        Log.e(TAG,"no newsList added to banner")
}

fun changeUrl(url: String): String {
    var outUrl = url
    if (!url.startsWith("https://")) {
        outUrl = if (url.startsWith("//")) {
            "https:$url"
        } else if (url.startsWith("http://")) {
            url.replace("http://", "https://")
        } else {
            "https://$url"
        }
    }
    return outUrl
}